import React, { useEffect, useState } from "react";
import { useLocation } from "@umijs/max";
import { useRequest } from "ahooks";
import { Descriptions, Divider, Space, Button, Modal } from "antd";
import { fetchOrderCheckRecordDetail, orderCheckRecordCheckOrder } from '../services';
import OrderVerifyRemark from "../modals/OrderVerifyRemark";
import { orderTypes } from "@/constants/types";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import { isTicketSettlement, isinsuranceFlag } from "@/utils/dictUtil";

const OrderVerifyDetail = () => {
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const id = searchParams.get('id');
  const [detail, setDetail] = useState<any>({});
  const { runAsync: fetchOrderVerifyDetail}  = useRequest(fetchOrderCheckRecordDetail, {manual: true});
  const { loading, runAsync: orderVerifyApi} = useRequest(orderCheckRecordCheckOrder, {manual: true});
  const [visible, setVisible] = useState(false);

  const orderVerifyRemarkProps = {
    visible,
    title: '订单审核',
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await orderVerifyApi({...params, id, checkStatus: '-1'});
      if (res?.code === '0') {
        orderVerifyRemarkProps.onCancel();
        fetchOrderVerifyDetail({id}).then(
          res => {
            setDetail(res || {});
          }
        );
      }
    }
  }

  const handleResolve = () => {
    Modal.confirm({
      title: '订单审核',
      content: '是否确定审核通过?',
      onOk: () => {
        orderVerifyApi({
          id,
          checkStatus: '2'
        }).then(
          res=> {
            if (res?.code === '0') {
              fetchOrderVerifyDetail({id}).then(
                res => {
                  setDetail(res || {});
                }
              );
            }
          }
        )
      }
    });
  }
  const handleReject = () => {
    setVisible(true);
  }

 

  const fields = [
    {
      title: '订单基本信息',
      column: 5,
      children: [
        {
          label: '订单号',
          value: 'orderCode',
        },
        {
          label: '订单状态',
          value: 'opStatusText',
        },
        {
          label: '外部单号',
          value: 'exOrderCode',
        },
        {
          label: '下单时间',
          value: 'orderTime',
          span: 2
        },
        {
          label: '客户编码',
          value: 'customerCode',
        },
        {
          label: '公司简称',
          value: 'customerName',
        },
        {
          label: '下单手机',
          value: 'mobile',
        },
        {
          label: '所属客服',
          value: 'serviceName',
        },
        {
          label: '所属销售',
          value: 'salesName',
        },
        {
          label: '产品',
          value: 'productName',
        },
        {
          label: '起始地',
          value: 'sportName',
        },
        {
          label: '目的地类型',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.destType} type="destType" />
        },
        {
          label: '派送方式',
          value: 'deliveryMethod',
        },
        {
          label: '周次',
          value: 'week',
        },
        {
          label: '国家',
          value: 'countryName',
        },
        {
          label: '目的港',
          value: 'dportName',
        },
        {
          label: '目的地',
          value: 'destCode',
        },
        {
          label: '年份',
          value: 'year',
        },
      ]
    },
    {
      title: '货物信息',
      column: 3,
      children: [
        {
          label: '品名',
          value: 'cargoName',
          span: 3
        },
        {
          label: '委托件数/箱',
          value: 'totalPieces',
        },
        {
          label: '委托总体积/CBM',
          value: 'totalVol',
        },
        {
          label: '委托总重量/KG',
          value: 'totalWeight',
        },
        {
          label: '实际总体积/CBM',
          value: 'inWhVol',
        },
        {
          label: '实际件数/箱',
          value: 'inWhPieces',
        },
        {
          label: '实际总重量/KG',
          value: 'inWhWeight',
        },
        {
          label: '计费重/KGS',
          value: 'feeWeight',
        },
        {
          label: '计费体积/CBM',
          value: 'feeVol',
        },
      ]
    },
    {
      title: '计费信息',
      column: 4,
      children: [
        {
          label: '计费方式',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.billMethod} type="paymethod" />
        },
        {
          label: '货重比',
          render: (record: orderTypes) => <span>{record?.weightRatio}</span>
        },
        {
          label: '建议卖价/元',
          value: 'oriPrice',
        },
        {
          label: '销售报价/元',
          value: 'price',
        },
        {
          label: '报关',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.bgMethod} type="customsMethod" />
        },
        {
          label: '报关费/元',
          value: 'bgFee',
        },
        {
          label: '提货',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.pickupWay} type="pickupMethod" />
        },
        {
          label: '提货费/元',
          value: 'pickupFee',
          render: (record: orderTypes) => <span>{String(record?.pickupFee) === '-1' ? '实报实销' : record?.pickupFee}</span>
        },
        {
          label: '商检费',
          value: 'cargoName',
        },
        {
          label: '商检费/元',
          value: 'cargoCheckFee',
        },
        {
          label: '附加费',
          value: 'cargoName',
        },
        {
          label: '附加费/元',
          value: 'additionalFee',
        },
        {
          label: '税金',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.taxFlag} type="taxes" />
        },
        {
          label: '税金/元',
          value: 'taxFee',
        },
        {
          label: '保险申报货值/元',
          value: 'declaredCargoValue',
          render: (record: orderTypes) => {
            return (
              <span>
                <span>{record?.declaredCargoValue} </span>
                {(Number(record?.declaredCargoValue) > 0 && Number(record?.totalWeight) > 0 && (Number(record?.declaredCargoValue)/Number(record?.totalWeight) >= 300)) && <span style={{color: 'red'}}>（高货值，需确认）</span>}
              </span>
            )
          }
        },
        {
          label: '保险费/元',
          value: 'insuranceFee',
        },
        {
          label: '优惠券',
          value: 'couponName',
        },
        {
          label: '优惠券/元',
          value: 'discountAmount',
        },
        {
          label: '最低起收标准',
          value: 'minTake', 
        },
        {
          label: <strong>总计费用/元</strong>,
          value: 'totalAmount',
        },
        {
          label: '合同结算方式',
          render: (record: orderTypes) => (
            <Space>
              <XlTableDictColumn value={record?.contractSettlementMethod} type="settlement" />
              {/* {isMonthSettlement(record?.contractSettlementMethod) &&  <XlTableDictColumn value={record?.contractPayNode} type="payDay" />} */}
              {isTicketSettlement(record?.contractSettlementMethod) &&  <XlTableDictColumn value={record?.contractPayNode} type="payNode" />}
            </Space>
          )
        },
        {
          label: '下单结算方式',
          render: (record: orderTypes) => (
            <Space>
              <XlTableDictColumn value={record?.settlementMethod} type="settlement" />
              {/* {isMonthSettlement(record?.settlementMethod) &&  <XlTableDictColumn value={record?.payDay} type="payDay" />} */}
              {isTicketSettlement(record?.settlementMethod) &&  <XlTableDictColumn value={record?.payNode} type="payNode" />}
            </Space>
          )
        },
      ]
    }
  ];

  useEffect(() => {
    if (id && location.pathname === '/order-manage/order-verify-detail') {
      fetchOrderVerifyDetail({id}).then(
        res => {
          setDetail(res || {});
        }
      );
    } else {
      setDetail({});
    }
  }, [id])

  return (
    <>
      {
        fields.map(v => (
          <>
            <Descriptions title={v.title} key={v.title} column={v.column}>
              {
                v.children.map((field: any) => (
                  <Descriptions.Item label={field.label} key={field.label} span={field.span}><strong>{field.render ? field.render(detail) : detail?.[field.value]}</strong></Descriptions.Item>
                ))
              }
            </Descriptions>
            <Divider />
          </>
        ))
      }
      {
        String(detail.checkStatus) === '1' && (
          <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center', padding: '20px'}}>
            <Space>
              <Button type="primary" key="审核通过" onClick={handleResolve} loading={loading}>审核通过</Button>
              <Button type="primary" key="审核不通过" danger onClick={handleReject} loading={loading}>审核不通过</Button>
            </Space>
          </div>
        )
      }
      {visible && <OrderVerifyRemark {...orderVerifyRemarkProps} />}
    </>
  );
}
export default OrderVerifyDetail;